package io.renren.modules.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.modules.web.dao.TestquestionDao;
import io.renren.modules.web.entity.CourseEntity;
import io.renren.modules.web.entity.TestquestionEntity;
import io.renren.modules.web.service.CategoryService;
import io.renren.modules.web.service.CourseService;
import io.renren.modules.web.service.TestquestionService;
import io.renren.modules.web.vo.CategoryLayerVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("testquestionService")
public class TestquestionServiceImpl extends ServiceImpl<TestquestionDao, TestquestionEntity> implements TestquestionService {

    @Autowired
    private CategoryService categoryService;
    @Autowired
    private CourseService courseService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String categoryId = (String) params.get("categoryId");
        String courseId = (String) params.get("courseId");
        String type = (String) params.get("type");
        String input = (String) params.get("input");


        IPage<TestquestionEntity> page = this.page(
                new Query<TestquestionEntity>().getPage(params),
                new QueryWrapper<TestquestionEntity>()
                        .eq(StringUtils.hasLength(categoryId), "category_id", categoryId)
                        .eq(StringUtils.hasLength(courseId), "course_id", courseId)
                        .eq(StringUtils.hasLength(type), "type", type)
                        .like(StringUtils.hasLength(input), "input", input)
                        .orderByDesc("update_time")
        );

        List<TestquestionEntity> records = page.getRecords();

        List<TestquestionEntity> collect = records.stream().peek(testquestionEntity -> {
            CategoryLayerVo categoryLayer = categoryService.getCategoryLayer(testquestionEntity.getCategoryId());
            List<String> categoryNameLayer = categoryLayer.getCategoryNameLayer();
            String join = String.join("/", categoryNameLayer);
            testquestionEntity.setCategoryName(join);
            CourseEntity courseEntity = courseService.getById(testquestionEntity.getCourseId());
            testquestionEntity.setCourseName(courseEntity.getName());
        }).collect(Collectors.toList());

        page.setRecords(collect);
        return new PageUtils(page);
    }

}